package com.tdam2011.grupo04.web;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.Util;
import com.tdam2011.grupo04.MasterListActivity;
import com.tdam2011.grupo04.R;
import com.tdam2011.grupo04.Sql;

import com.tdam2011.grupo04.entidades.Amigo;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.QuickContactBadge;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.content.DialogInterface.OnClickListener;

public class AsignarContactoAmigo extends MasterListActivity implements
		OnItemClickListener {
	// application id from facebook.com/developers
	public static final String APP_ID = "146284105514859";
	// log tag for any log.x statements
	public static final String TAG = "FACEBOOK CONNECT";
	// permissions array
	private static final String[] PERMS = new String[] { "publish_actions",
			"publish_stream", "email", "user_relationships",
			"user_online_presence", "friends_birthday", "friends_photos",
			"friends_location", "friends_about_me", "friends_hometown" };
	// facebook vars
	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;
	private ListaAmigosAdapter adapter;

	private String amigo;
	private String contacto;
	private boolean privado;
	private TextView txt_nombre;

	private String cuenta;
	
	private PublicarMuroRequestListener pmrl;
	public ArrayList<Amigo> amigosAuxiliar = new ArrayList<Amigo>();

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);		
		setContentView(R.layout.asignar_contacto_amigo);
		
		adapter = new ListaAmigosAdapter();
		setListAdapter(adapter);

		this.getListView().setTextFilterEnabled(true);

		Bundle extras = getIntent().getExtras();
		if (extras != null)
			contacto = (String) extras.get("contacto");

		this.getListView().setOnItemClickListener(this);

		  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		  prefs.getString("Token", null);
		  mFacebook = new Facebook(APP_ID);
		  
		  mFacebook.setAccessToken(prefs.getString("Token", null));

		//mFacebook.authorize(this, PERMS, new LoginDialogListener());
		
		mAsyncRunner = new AsyncFacebookRunner(mFacebook);

		pmrl= new PublicarMuroRequestListener();
		mAsyncRunner.request("me", pmrl);
		
	}

	@Override
	protected void publishFilterApplied() {
		super.publishFilterApplied();
		filtrar();//lo del filtro
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialogo = null;
		dialogo = crearDialogoConfirmacion();
		return dialogo;
	}

	private Dialog crearDialogoConfirmacion() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setTitle("Confirmacion");
		builder.setMessage("�Desea asignar este amigo al contacto?");
		builder.setPositiveButton("Si", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Sql sql = new Sql(AsignarContactoAmigo.this);
				sql.addContactoAmigo(contacto, amigo, cuenta, privado);
				sql.close();
				finish();
			}
		});
		builder.setNegativeButton("No", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});

		return builder.create();
	}

	private class PublicarMuroRequestListener implements RequestListener {

		public void onComplete(String response, Object state) {

			adapter.clearList();
			
			while(!mFacebook.isSessionValid())
				Log.i("Esperando conexion a facebook","");
			
			runOnUiThread(new Runnable() {
				public void run() {
					setProgressBarIndeterminateVisibility(true);
				}
			});
			Bundle bdle = new Bundle();
			bdle.putString("fields", "name, picture, hometown, username");

			String graphpath = "me/friends";
			try {
				if (mFacebook.isSessionValid()) {
					JSONObject json = Util.parseJson(mFacebook.request(
							graphpath, bdle));
					JSONArray jArray = json.getJSONArray("data");
					JSONObject j;
					for (int i = 0; i < jArray.length(); i++) {
						JSONObject json_data = jArray.getJSONObject(i);
						Log.i("data:", json_data.toString());

						Amigo amigo = new Amigo();
						try{
						amigo.setId(json_data.getString("username"));
						}
						catch(JSONException e){
							amigo.setId(json_data.getString("id"));
							amigo.setPrivado(true);
						}
						amigo.setNombre(json_data.getString("name"));
						
						if((amigo.getNombre() != null || amigo.getId() != null) 
								&& (!contactFilterApplied 
										|| amigo.getNombre().toLowerCase().startsWith(contactFilter) 
										|| amigo.getId().toLowerCase().startsWith(contactFilter))){
							try {
								j = json_data.getJSONObject("hometown");
								amigo.setLocalidad(j.getString("name"));
							} catch (Exception e) {
								amigo.setLocalidad("Localidad Desconocida");
							}
							j = json_data.getJSONObject("picture");
							j = j.getJSONObject("data");
							amigo.setFoto(j.getString("url"));
	
							adapter.addAmigo(amigo);
							amigosAuxiliar.add(amigo);
						}
					}

					Bundle bdle2 = new Bundle();
					bdle2.putString("fields", "id");
					String graphpath2 = "me";
					JSONObject json2 = Util.parseJson(mFacebook.request(graphpath2, bdle2));
					cuenta = json2.getString("id");
					
					runOnUiThread(new Runnable() {
						public void run() {
							adapter.ordenar();
							adapter.notifyDataSetChanged();
						}
					});
				}
			} catch (FacebookError e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			runOnUiThread(new Runnable() {
				public void run() {
					setProgressBarIndeterminateVisibility(false);
				}
			});
		}

		@Override
		public void onIOException(IOException e, Object state) {}

		@Override
		public void onFileNotFoundException(FileNotFoundException e, Object state) {}

		@Override
		public void onMalformedURLException(MalformedURLException e, Object state) {}

		@Override
		public void onFacebookError(FacebookError e, Object state) {}
	}
	
	public void filtrar() {
		adapter.clearList();
		for (Amigo amigo : amigosAuxiliar) {

			if ((amigo.getNombre() != null || amigo.getId() != null)
					&& (!contactFilterApplied
							|| amigo.getNombre().toLowerCase()
									.startsWith(contactFilter) || amigo.getId()
							.toLowerCase().startsWith(contactFilter))) {
				adapter.addAmigo(amigo);
			}
		}
		adapter.ordenar();
		adapter.notifyDataSetChanged();
	}

	private class LoginDialogListener implements DialogListener {

		public void onComplete(Bundle values) {
			// setearControles();
		}


		public void onFacebookError(FacebookError e) {}

		public void onError(DialogError e) {}

		public void onCancel() {}

	}

	class ListaAmigosAdapter extends BaseAdapter implements Filterable{
		private ArrayList<Amigo> amigos;
		private LayoutInflater inflater;
		private ContactFilter filter;

		
		public void ordenar(){
			Collections.sort(amigos, new CustomComparator());		
		}
		
		public class CustomComparator implements Comparator<Amigo> {
		    @Override
		    public int compare(Amigo a1, Amigo a2) {
		        return a1.getNombre().compareTo(a2.getNombre());
		    }
		}
		
		public ListaAmigosAdapter() {
			amigos = new ArrayList<Amigo>();
			inflater = LayoutInflater.from(AsignarContactoAmigo.this);
		}

		public void addAmigo(Amigo amigo) {
			if (amigo != null)
				amigos.add(amigo);
		}

		public int getCount() {
			return amigos.size();
		}

		public Object getItem(int position) {
			return amigos.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public void clearList() {
			amigos.clear();
		}

		class Holder {
			private TextView txt_contacto;
			private TextView txt_telefono;
			private TextView txt_correo;
			private QuickContactBadge imagen_contacto;
			private ImageView icon_telefono;
			private ImageView icon_mail;
			private ImageView img_siguiente;
		}

		public View getView(final int position, View convertView, ViewGroup arg2) {
			Holder holder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.agenda_contacto, null);
				holder = new Holder();
				holder.imagen_contacto = (QuickContactBadge) convertView
						.findViewById(R.id.imagen_contacto);
				holder.txt_contacto = (TextView) convertView
						.findViewById(R.id.txt_contacto);
				holder.txt_telefono = (TextView) convertView
						.findViewById(R.id.txt_telefono);
				holder.txt_correo = (TextView) convertView
						.findViewById(R.id.txt_mail);
				/*holder.icon_telefono = (ImageView) convertView
						.findViewById(R.id.icon_telefono);
				holder.icon_mail = (ImageView) convertView
						.findViewById(R.id.icon_mail); */
				holder.img_siguiente = (ImageView) convertView
						.findViewById(R.id.btn_agendaSiguiente);
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}

			final Amigo amigo = (Amigo) getItem(position);

			holder.txt_contacto.setText(amigo.getNombre());
			holder.txt_correo.setText(amigo.getLocalidad());

			try {
				URL urlFoto;
				Bitmap bmp;
				urlFoto = new URL(amigo.getFoto());
				bmp = loadFromUrl(urlFoto);
				holder.imagen_contacto
						.setMode(ContactsContract.QuickContact.MODE_SMALL);
				holder.imagen_contacto.setImageBitmap(bmp);

			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return convertView;
		}

		private Bitmap loadFromUrl(URL link) {
			Bitmap bitmap = null;
			InputStream in = null;
			try {
				in = link.openConnection().getInputStream();
				bitmap = BitmapFactory.decodeStream(in, null, null);
				in.close();
			} catch (IOException e) {
			}
			return bitmap;
		}

		@Override
		public Filter getFilter() {
			if (filter == null) {
				filter = new ContactFilter();
			}
			return filter;
		}
	}

	// @Override
	// public Filter getFilter() {
	// if (filter == null) {
	// filter = new ContactFilter();
	// }
	// return filter;
	// }
	// }
	//
	// private void publishFilterApplied() {
	// if (contactFilter == null || contactFilter.length() == 0) {
	// contactFilterApplied = false;
	// } else {
	// contactFilterApplied = true;
	// }
	// this.cargarAgenda("STARRED DESC");
	// }
	//
	// class ContactFilter extends Filter {
	//
	// @Override
	// protected FilterResults performFiltering(CharSequence constraint) {
	// String filter = constraint.toString().toLowerCase().trim();
	// contactFilter = filter;
	// return null;
	// }
	//
	// @Override
	// protected void publishResults(CharSequence constraint,
	// FilterResults results) {
	// publishFilterApplied();
	// }
	// }

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		getMenuInflater().inflate(R.menu.activity_asignar_contacto_amigo, menu);
//		return true;
//	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		amigo = ((Amigo) adapter.getItem(position)).getId();
		privado = ((Amigo) adapter.getItem(position)).getPrivado();
		showDialog(1);
	}

}
